/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.IllegalOrphanException;
import controller.exceptions.NonexistentEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.Usuarios;
import model.Tipocredito;
import model.Pagos;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.Creditos;

/**
 *
 * @author AlexanderDiaz
 */
public class CreditosJpaController implements Serializable {

    public CreditosJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Creditos creditos) throws RollbackFailureException, Exception {
        if (creditos.getPagosCollection() == null) {
            creditos.setPagosCollection(new ArrayList<Pagos>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Usuarios idEmpleadoTitular = creditos.getIdEmpleadoTitular();
            if (idEmpleadoTitular != null) {
                idEmpleadoTitular = em.getReference(idEmpleadoTitular.getClass(), idEmpleadoTitular.getIdUsuario());
                creditos.setIdEmpleadoTitular(idEmpleadoTitular);
            }
            Tipocredito idTipoCredito = creditos.getIdTipoCredito();
            if (idTipoCredito != null) {
                idTipoCredito = em.getReference(idTipoCredito.getClass(), idTipoCredito.getIdTipo());
                creditos.setIdTipoCredito(idTipoCredito);
            }
            Usuarios idEmpleadoAdministrador = creditos.getIdEmpleadoAdministrador();
            if (idEmpleadoAdministrador != null) {
                idEmpleadoAdministrador = em.getReference(idEmpleadoAdministrador.getClass(), idEmpleadoAdministrador.getIdUsuario());
                creditos.setIdEmpleadoAdministrador(idEmpleadoAdministrador);
            }
            Usuarios idEmpleadoCodeudor = creditos.getIdEmpleadoCodeudor();
            if (idEmpleadoCodeudor != null) {
                idEmpleadoCodeudor = em.getReference(idEmpleadoCodeudor.getClass(), idEmpleadoCodeudor.getIdUsuario());
                creditos.setIdEmpleadoCodeudor(idEmpleadoCodeudor);
            }
            Collection<Pagos> attachedPagosCollection = new ArrayList<Pagos>();
            for (Pagos pagosCollectionPagosToAttach : creditos.getPagosCollection()) {
                pagosCollectionPagosToAttach = em.getReference(pagosCollectionPagosToAttach.getClass(), pagosCollectionPagosToAttach.getIdPago());
                attachedPagosCollection.add(pagosCollectionPagosToAttach);
            }
            creditos.setPagosCollection(attachedPagosCollection);
            em.persist(creditos);
            if (idEmpleadoTitular != null) {
                idEmpleadoTitular.getCreditosCollection().add(creditos);
                idEmpleadoTitular = em.merge(idEmpleadoTitular);
            }
            if (idTipoCredito != null) {
                idTipoCredito.getCreditosCollection().add(creditos);
                idTipoCredito = em.merge(idTipoCredito);
            }
            if (idEmpleadoAdministrador != null) {
                idEmpleadoAdministrador.getCreditosCollection().add(creditos);
                idEmpleadoAdministrador = em.merge(idEmpleadoAdministrador);
            }
            if (idEmpleadoCodeudor != null) {
                idEmpleadoCodeudor.getCreditosCollection().add(creditos);
                idEmpleadoCodeudor = em.merge(idEmpleadoCodeudor);
            }
            for (Pagos pagosCollectionPagos : creditos.getPagosCollection()) {
                Creditos oldIdCreditoOfPagosCollectionPagos = pagosCollectionPagos.getIdCredito();
                pagosCollectionPagos.setIdCredito(creditos);
                pagosCollectionPagos = em.merge(pagosCollectionPagos);
                if (oldIdCreditoOfPagosCollectionPagos != null) {
                    oldIdCreditoOfPagosCollectionPagos.getPagosCollection().remove(pagosCollectionPagos);
                    oldIdCreditoOfPagosCollectionPagos = em.merge(oldIdCreditoOfPagosCollectionPagos);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Creditos creditos) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Creditos persistentCreditos = em.find(Creditos.class, creditos.getIdCredito());
            Usuarios idEmpleadoTitularOld = persistentCreditos.getIdEmpleadoTitular();
            Usuarios idEmpleadoTitularNew = creditos.getIdEmpleadoTitular();
            Tipocredito idTipoCreditoOld = persistentCreditos.getIdTipoCredito();
            Tipocredito idTipoCreditoNew = creditos.getIdTipoCredito();
            Usuarios idEmpleadoAdministradorOld = persistentCreditos.getIdEmpleadoAdministrador();
            Usuarios idEmpleadoAdministradorNew = creditos.getIdEmpleadoAdministrador();
            Usuarios idEmpleadoCodeudorOld = persistentCreditos.getIdEmpleadoCodeudor();
            Usuarios idEmpleadoCodeudorNew = creditos.getIdEmpleadoCodeudor();
            Collection<Pagos> pagosCollectionOld = persistentCreditos.getPagosCollection();
            Collection<Pagos> pagosCollectionNew = creditos.getPagosCollection();
            List<String> illegalOrphanMessages = null;
            for (Pagos pagosCollectionOldPagos : pagosCollectionOld) {
                if (!pagosCollectionNew.contains(pagosCollectionOldPagos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Pagos " + pagosCollectionOldPagos + " since its idCredito field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idEmpleadoTitularNew != null) {
                idEmpleadoTitularNew = em.getReference(idEmpleadoTitularNew.getClass(), idEmpleadoTitularNew.getIdUsuario());
                creditos.setIdEmpleadoTitular(idEmpleadoTitularNew);
            }
            if (idTipoCreditoNew != null) {
                idTipoCreditoNew = em.getReference(idTipoCreditoNew.getClass(), idTipoCreditoNew.getIdTipo());
                creditos.setIdTipoCredito(idTipoCreditoNew);
            }
            if (idEmpleadoAdministradorNew != null) {
                idEmpleadoAdministradorNew = em.getReference(idEmpleadoAdministradorNew.getClass(), idEmpleadoAdministradorNew.getIdUsuario());
                creditos.setIdEmpleadoAdministrador(idEmpleadoAdministradorNew);
            }
            if (idEmpleadoCodeudorNew != null) {
                idEmpleadoCodeudorNew = em.getReference(idEmpleadoCodeudorNew.getClass(), idEmpleadoCodeudorNew.getIdUsuario());
                creditos.setIdEmpleadoCodeudor(idEmpleadoCodeudorNew);
            }
            Collection<Pagos> attachedPagosCollectionNew = new ArrayList<Pagos>();
            for (Pagos pagosCollectionNewPagosToAttach : pagosCollectionNew) {
                pagosCollectionNewPagosToAttach = em.getReference(pagosCollectionNewPagosToAttach.getClass(), pagosCollectionNewPagosToAttach.getIdPago());
                attachedPagosCollectionNew.add(pagosCollectionNewPagosToAttach);
            }
            pagosCollectionNew = attachedPagosCollectionNew;
            creditos.setPagosCollection(pagosCollectionNew);
            creditos = em.merge(creditos);
            if (idEmpleadoTitularOld != null && !idEmpleadoTitularOld.equals(idEmpleadoTitularNew)) {
                idEmpleadoTitularOld.getCreditosCollection().remove(creditos);
                idEmpleadoTitularOld = em.merge(idEmpleadoTitularOld);
            }
            if (idEmpleadoTitularNew != null && !idEmpleadoTitularNew.equals(idEmpleadoTitularOld)) {
                idEmpleadoTitularNew.getCreditosCollection().add(creditos);
                idEmpleadoTitularNew = em.merge(idEmpleadoTitularNew);
            }
            if (idTipoCreditoOld != null && !idTipoCreditoOld.equals(idTipoCreditoNew)) {
                idTipoCreditoOld.getCreditosCollection().remove(creditos);
                idTipoCreditoOld = em.merge(idTipoCreditoOld);
            }
            if (idTipoCreditoNew != null && !idTipoCreditoNew.equals(idTipoCreditoOld)) {
                idTipoCreditoNew.getCreditosCollection().add(creditos);
                idTipoCreditoNew = em.merge(idTipoCreditoNew);
            }
            if (idEmpleadoAdministradorOld != null && !idEmpleadoAdministradorOld.equals(idEmpleadoAdministradorNew)) {
                idEmpleadoAdministradorOld.getCreditosCollection().remove(creditos);
                idEmpleadoAdministradorOld = em.merge(idEmpleadoAdministradorOld);
            }
            if (idEmpleadoAdministradorNew != null && !idEmpleadoAdministradorNew.equals(idEmpleadoAdministradorOld)) {
                idEmpleadoAdministradorNew.getCreditosCollection().add(creditos);
                idEmpleadoAdministradorNew = em.merge(idEmpleadoAdministradorNew);
            }
            if (idEmpleadoCodeudorOld != null && !idEmpleadoCodeudorOld.equals(idEmpleadoCodeudorNew)) {
                idEmpleadoCodeudorOld.getCreditosCollection().remove(creditos);
                idEmpleadoCodeudorOld = em.merge(idEmpleadoCodeudorOld);
            }
            if (idEmpleadoCodeudorNew != null && !idEmpleadoCodeudorNew.equals(idEmpleadoCodeudorOld)) {
                idEmpleadoCodeudorNew.getCreditosCollection().add(creditos);
                idEmpleadoCodeudorNew = em.merge(idEmpleadoCodeudorNew);
            }
            for (Pagos pagosCollectionNewPagos : pagosCollectionNew) {
                if (!pagosCollectionOld.contains(pagosCollectionNewPagos)) {
                    Creditos oldIdCreditoOfPagosCollectionNewPagos = pagosCollectionNewPagos.getIdCredito();
                    pagosCollectionNewPagos.setIdCredito(creditos);
                    pagosCollectionNewPagos = em.merge(pagosCollectionNewPagos);
                    if (oldIdCreditoOfPagosCollectionNewPagos != null && !oldIdCreditoOfPagosCollectionNewPagos.equals(creditos)) {
                        oldIdCreditoOfPagosCollectionNewPagos.getPagosCollection().remove(pagosCollectionNewPagos);
                        oldIdCreditoOfPagosCollectionNewPagos = em.merge(oldIdCreditoOfPagosCollectionNewPagos);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = creditos.getIdCredito();
                if (findCreditos(id) == null) {
                    throw new NonexistentEntityException("The creditos with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Creditos creditos;
            try {
                creditos = em.getReference(Creditos.class, id);
                creditos.getIdCredito();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The creditos with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Pagos> pagosCollectionOrphanCheck = creditos.getPagosCollection();
            for (Pagos pagosCollectionOrphanCheckPagos : pagosCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Creditos (" + creditos + ") cannot be destroyed since the Pagos " + pagosCollectionOrphanCheckPagos + " in its pagosCollection field has a non-nullable idCredito field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Usuarios idEmpleadoTitular = creditos.getIdEmpleadoTitular();
            if (idEmpleadoTitular != null) {
                idEmpleadoTitular.getCreditosCollection().remove(creditos);
                idEmpleadoTitular = em.merge(idEmpleadoTitular);
            }
            Tipocredito idTipoCredito = creditos.getIdTipoCredito();
            if (idTipoCredito != null) {
                idTipoCredito.getCreditosCollection().remove(creditos);
                idTipoCredito = em.merge(idTipoCredito);
            }
            Usuarios idEmpleadoAdministrador = creditos.getIdEmpleadoAdministrador();
            if (idEmpleadoAdministrador != null) {
                idEmpleadoAdministrador.getCreditosCollection().remove(creditos);
                idEmpleadoAdministrador = em.merge(idEmpleadoAdministrador);
            }
            Usuarios idEmpleadoCodeudor = creditos.getIdEmpleadoCodeudor();
            if (idEmpleadoCodeudor != null) {
                idEmpleadoCodeudor.getCreditosCollection().remove(creditos);
                idEmpleadoCodeudor = em.merge(idEmpleadoCodeudor);
            }
            em.remove(creditos);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Creditos> findCreditosEntities() {
        return findCreditosEntities(true, -1, -1);
    }

    public List<Creditos> findCreditosEntities(int maxResults, int firstResult) {
        return findCreditosEntities(false, maxResults, firstResult);
    }

    private List<Creditos> findCreditosEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Creditos.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Creditos findCreditos(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Creditos.class, id);
        } finally {
            em.close();
        }
    }

    public int getCreditosCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Creditos> rt = cq.from(Creditos.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
